package com.txtsqlclient.ui;

import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.txtsqlclient.dataaccess.database.connection.ConnectionException;
import com.txtsqlclient.dataaccess.database.connection.ConnectionFactory;
import com.txtsqlclient.ui.exception.SubInterfaceException;
import com.txtsqlclient.ui.factory.SubInterfaceFactory;
import com.txtsqlclient.ui.helper.OutputHelper;
import com.txtsqlclient.ui.si.SubInterface;
import com.txtsqlclient.ui.vo.Session;

/**
 * @author spadda
 */
public class Sql {

	private Session session = new Session();

	private static Log LOGGER = LogFactory.getLog(Sql.class);

	protected SubInterfaceFactory getSubInterfaceFactory() {
		return SubInterfaceFactory.getInstance();
	}

	protected ConnectionFactory getConnectionFactory() {
		return ConnectionFactory.getInstance();
	}

	public static void main(final String[] args) throws ConnectionException,
			IOException {
		final Sql s = new Sql();
		s.getDataSourceInfo();
		s.handleCommands();
	}

	/**
	 * @param s
	 */
	protected void handleCommands() {
		LOGGER.trace("Starting to handle commands");
		while (this.session.isActive()) {
			SubInterface si = getSubInterfaceFactory().getCommandSubInterface(
					null);
			try {
				si.process(this.session);
			} catch (SubInterfaceException e) {
				System.out.println(OutputHelper.printException(e));
				LOGGER.error("Error processing command", e);
			}
		}
		this.exit();
	}

	protected void getDataSourceInfo() {
		LOGGER.trace("Starting to get data source info");
		while (this.session.getDataSource() == null) {
			SubInterface si = getSubInterfaceFactory()
					.getDataSourceSubInterface(null);
			try {
				si.process(this.session);
			} catch (SubInterfaceException e) {
				System.out.println(OutputHelper.printException(e));
				LOGGER.error("Error reading Data Source information", e);
			}
		}
		LOGGER.debug("Obtained data source info: "
				+ this.session.getDataSource());
	}

	protected void exit() {
		LOGGER.debug("Recieved exit command.");
		try {
			getConnectionFactory().cleanUp();
		} catch (ConnectionException e) {
			System.out.println("Error while closing the database connection:");
			System.out.println(OutputHelper.printException(e));
			LOGGER.error("Error while closing the database connection", e);
		}
		LOGGER.debug("Cleaned up connections. Exiting now.");
	}
}